package ar.com.ford.it.fullEconomics.view.action;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.CommodityFacade;
import ar.com.ford.it.fullEconomics.facade.CostStructureFacade;
import ar.com.ford.it.fullEconomics.facade.PaymentPolicyFacade;
import ar.com.ford.it.fullEconomics.facade.SupplierFacade;
import ar.com.ford.it.fullEconomics.persistence.dto.Teese05Paypolvers;
import ar.com.ford.it.fullEconomics.persistence.dto.Teess01Supplier;
import ar.com.ford.it.fullEconomics.struct.FullEconomicWrapStruct;
import ar.com.ford.it.fullEconomics.struct.PaymentPolicyCreateStruct;
import ar.com.ford.it.fullEconomics.util.FullEconomicsDateUtil;
import ar.com.ford.it.fullEconomics.view.form.PaymentPolicyDefinitionForm;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.facade.FacadeProvider;
import ar.com.ford.it.webengine.struts.AbstractBaseAction;
import ar.com.ford.it.webengine.struts.FordActionMapping;
import ar.com.ford.it.webengine.websession.WebSession;

public class PaymentPolicyDefinitionAction extends AbstractBaseAction {

    public ActionForward initPage(FordActionMapping mapping,
                                  ActionForm actionForm,
                                  HttpServletRequest request,
                                  HttpServletResponse response,
                                  WebSession webSession, ActionMessages msgs,
                                  ActionMessages warns, ActionMessages errorMsgs) {
        this.setCombos(request, webSession);
        PaymentPolicyDefinitionForm form = (PaymentPolicyDefinitionForm) actionForm;
        form.resetForm();
        form.setFullEconomic((FullEconomicWrapStruct) request.getAttribute("fullEconomic"));
        Teese05Paypolvers payPolVers = new Teese05Paypolvers();
        payPolVers.setEese05PpyverVersionNumberK(new Integer("1"));
        form.setPayPolVersSelected(payPolVers);
        form.setOperation("newPayPol");
        return mapping.findForward("success");
    }

    public ActionForward newVersion(FordActionMapping mapping,
                                    ActionForm actionForm,
                                    HttpServletRequest request,
                                    HttpServletResponse response,
                                    WebSession webSession, ActionMessages msgs,
                                    ActionMessages warns,
                                    ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        this.setCombos(request, webSession);
        PaymentPolicyDefinitionForm form = (PaymentPolicyDefinitionForm) actionForm;
        form.resetForm();
        form.setFullEconomic((FullEconomicWrapStruct) request.getAttribute("fullEconomic"));
        PaymentPolicyFacade facade = (PaymentPolicyFacade) FacadeProvider
                .getFacade(request, PaymentPolicyFacade.class);
        try {
            Teese05Paypolvers version = new Teese05Paypolvers();
            Teese05Paypolvers versionSelected = (Teese05Paypolvers) request
                    .getAttribute("payPolVersSelected");
            Teese05Paypolvers prevAprovedVersion = facade
                    .getPrevAprovedVersion(versionSelected);
            form.setPrevPayPolVers(prevAprovedVersion);
            version.setTeese04Paypolicy(versionSelected.getTeese04Paypolicy());
            form.setPayPolVersSelected(version);
            form.setOperation("newVersion");
            form.setPaymentPolicyDetails();
            if(prevAprovedVersion != null)
                form.setPrevVersionDetails();
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    public ActionForward editVersion(FordActionMapping mapping,
                                     ActionForm actionForm,
                                     HttpServletRequest request,
                                     HttpServletResponse response,
                                     WebSession webSession,
                                     ActionMessages msgs, ActionMessages warns,
                                     ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        this.setCombos(request, webSession);
        PaymentPolicyDefinitionForm form = (PaymentPolicyDefinitionForm) actionForm;
        PaymentPolicyFacade facade = (PaymentPolicyFacade) FacadeProvider
                .getFacade(request, PaymentPolicyFacade.class);
        form.resetForm();
        form.setFullEconomic((FullEconomicWrapStruct) request.getAttribute("fullEconomic"));
        try {
            form.setPayPolVersSelected((Teese05Paypolvers) request
                    .getAttribute("payPolVersSelected"));
            form.setPrevPayPolVers(facade.getPrevAprovedVersion(form
                    .getPayPolVersSelected()));
            form.setOperation("editVersion");
            form.setPaymentPolicyDetails();
            form.setVersionDetails();
            if(form.getPrevPayPolVers() != null)
                form.setPrevVersionDetails();
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    public ActionForward save(FordActionMapping mapping, ActionForm actionForm,
                              HttpServletRequest request,
                              HttpServletResponse response,
                              WebSession webSession, ActionMessages msgs,
                              ActionMessages warns, ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        MessageResources messageResources = (MessageResources) getResources(request);
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        PaymentPolicyDefinitionForm form = (PaymentPolicyDefinitionForm) actionForm;
        PaymentPolicyFacade facade = (PaymentPolicyFacade) FacadeProvider
                .getFacade(request, PaymentPolicyFacade.class);
        SupplierFacade suppFacade = (SupplierFacade) FacadeProvider.getFacade(
                request, SupplierFacade.class);
        CommodityFacade commFacade = (CommodityFacade) FacadeProvider
                .getFacade(request, CommodityFacade.class);
        String operation = form.getOperation();
        boolean allOk = true;
        Teese05Paypolvers ret = null;
        if (operation.equals("newPayPol")) {
            try {
                PaymentPolicyCreateStruct payPol = new PaymentPolicyCreateStruct();
                payPol.setDateIn(form.getDateIn());
                payPol.setDateOut(form.getDateOut());
                payPol.setValue(form.getValue());
                payPol.setUser(user);
				payPol.setObservations(form.getObservations());
                //if (form.getAppliesToSup().equals("true")) {  // ant
                if (form.getSupplierCode().length() != 0) {  // max 
                    Teess01Supplier supplier = new Teess01Supplier();
                    supplier.setEess01PlantCodeC(user.getTeesg01Plant());
                    supplier.setEess01SupplierClassCodeC(form
                            .getSupplierClass());
                    supplier.setEess01SupplierCodeC(form.getSupplierCode());

                    if (suppFacade.getSupplierByPk(supplier) != null) {
                        payPol.setSupplierClass(form.getSupplierClass());
                        payPol.setSupplierCode(form.getSupplierCode());
                        payPol.setAppliesTo("supplier");
                    } else {
                        am
                                .add(
                                        ActionMessages.GLOBAL_MESSAGE,
                                        new ActionMessage(
                                                "customMessage",
                                                messageResources
                                                        .getMessage("paymentPolicyDefinition.error.invalidSupplier")));
                        saveErrors(request, am);
                        allOk = false;
                    }
                }
                // if (form.getItemScope().equals("I")) {
                if (form.getItem() != null ) { 
                    payPol.setItem(form.getItem());
                    //payPol.setItemCategory(form.getItemCategory());
                } 
                   
                if (form.getItemCategory() != null) {
                    payPol.setItemCategory(form.getItemCategory());
                }
                /* else {
                    am
                            .add(
                                    ActionMessages.GLOBAL_MESSAGE,
                                    new ActionMessage(
                                            "customMessage",
                                            messageResources
                                                    .getMessage("paymentPolicyDefinition.error.invalidItemScope")));
                    saveErrors(request, am);
                    allOk = false;
                }*/
                if (allOk) {
                    ret = facade.createPayPol(payPol);
                }
            } catch (FullEconomicsException e) {
                am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                        .getMessageResource()));
                saveErrors(request, am);
            }
        } else if (operation.equalsIgnoreCase("newVersion")) {
            try {
                Teese05Paypolvers newVersion = new Teese05Paypolvers();
                newVersion.setTeese04Paypolicy(form.getPayPolVersSelected()
                        .getTeese04Paypolicy());
                Calendar calDateIn = FullEconomicsDateUtil.format(form
                        .getDateIn());
                Calendar calDateOut = FullEconomicsDateUtil.format(form
                        .getDateOut());
                newVersion.setEese05PpyverInDateY(new Timestamp(calDateIn
                        .getTimeInMillis()));
                if (calDateOut == null)
                    newVersion.setEese05PpyverOutDateY(FullEconomicsDateUtil
                            .maxDate());
                else
                    newVersion.setEese05PpyverOutDateY(new Timestamp(calDateOut
                            .getTimeInMillis()));
                newVersion.setEese05PpyverPercentP(new BigDecimal(form
                        .getValue()));
                newVersion.setEese05PpyverCommentsX(form.getObservations());

                ret = facade.createNewVersion(newVersion, user);
            } catch (FullEconomicsException e) {
                am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                        .getMessageResource()));
                saveErrors(request, am);
            }
        } else if (operation.equalsIgnoreCase("editVersion")) {
            try {
                Teese05Paypolvers version = form.getPayPolVersSelected();
                Calendar calDateIn = FullEconomicsDateUtil.format(form
                        .getDateIn());
                Calendar calDateOut = FullEconomicsDateUtil.format(form
                        .getDateOut());
                version.setEese05PpyverInDateY(new Timestamp(calDateIn
                        .getTimeInMillis()));
                if (calDateOut == null)
                    version.setEese05PpyverOutDateY(FullEconomicsDateUtil
                            .maxDate());
                else
                    version.setEese05PpyverOutDateY(new Timestamp(calDateOut
                            .getTimeInMillis()));
                version
                        .setEese05PpyverPercentP(new BigDecimal(form.getValue()));
                version.setEese05PpyverCommentsX(form.getObservations());
                facade.updateVersion(version, user);
                ret = version;
            } catch (FullEconomicsException e) {
                am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                        .getMessageResource()));
                saveErrors(request, am);
            }
        }
        request.setAttribute("payPolVersSelected", ret);
        request.setAttribute("fullEconomic", form.getFullEconomic());
        if (allOk)
            return mapping.findForward("success");
        else
            return mapping.findForward("error");
    }

    private void setCombos(HttpServletRequest request, WebSession webSession) {
        ActionMessages am = new ActionMessages();
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();

        CommodityFacade commFacade = (CommodityFacade) FacadeProvider
                .getFacade(request, CommodityFacade.class);
        CostStructureFacade cstrFacade = (CostStructureFacade) FacadeProvider
                .getFacade(request, CostStructureFacade.class);
        request.getSession().setAttribute("partClassColl",
                commFacade.getPartClases());

        try {
            request.getSession().setAttribute(
                    "commodityColl",
                    commFacade.findCommodities(null, null, user
                            .getTeesg01Plant()));
            request.getSession().setAttribute("ItemCategoryColl",
                    cstrFacade.findAllItemCategories(user.getTeesg01Plant()));
            request.getSession().setAttribute(
                    "ItemColl",
                    cstrFacade.findItems("-1", null, null, user
                            .getTeesg01Plant()));
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
    }

    public ActionForward clearFields(FordActionMapping mapping,
                                     ActionForm actionForm,
                                     HttpServletRequest request,
                                     HttpServletResponse response,
                                     WebSession webSession,
                                     ActionMessages msgs, ActionMessages warns,
                                     ActionMessages errorMsgs) {

        PaymentPolicyDefinitionForm form = (PaymentPolicyDefinitionForm) actionForm;
        form.resetForm();
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward findItems(FordActionMapping mapping,
                                   ActionForm actionForm,
                                   HttpServletRequest request,
                                   HttpServletResponse response,
                                   WebSession webSession, ActionMessages msgs,
                                   ActionMessages warns,
                                   ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        CostStructureFacade cstrFacade = (CostStructureFacade) FacadeProvider
                .getFacade(request, CostStructureFacade.class);
        try {
            String itemCat = request.getParameter("itemCategory");
            Collection itemList = cstrFacade.findApprovedItems(user
                    .getTeesg01Plant(), itemCat);
            request.getSession().setAttribute("itemColl", itemList);
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward propose(FordActionMapping mapping,
                                 ActionForm actionForm,
                                 HttpServletRequest request,
                                 HttpServletResponse response,
                                 WebSession webSession, ActionMessages msgs,
                                 ActionMessages warns, ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        PaymentPolicyDefinitionForm form = (PaymentPolicyDefinitionForm) actionForm;
        PaymentPolicyFacade facade = (PaymentPolicyFacade) FacadeProvider
                .getFacade(request, PaymentPolicyFacade.class);
        Teese05Paypolvers payPolVers = form.getPayPolVersSelected();
        try {
            
            Calendar calDateIn = FullEconomicsDateUtil.format(form.getDateIn());
            Calendar calDateOut = FullEconomicsDateUtil.format(form
                    .getDateOut());
            payPolVers.setEese05PpyverInDateY(new Timestamp(calDateIn
                    .getTimeInMillis()));
            payPolVers.setEese05PpyverOutDateY(new Timestamp(calDateOut
                    .getTimeInMillis()));
            payPolVers.setEese05PpyverPercentP(new BigDecimal(form.getValue()));
            payPolVers.setEese05PpyverCommentsX(form.getObservations());

            facade.updateVersion(payPolVers, user);
            facade.proposePaymentPolicy(payPolVers, user);

            payPolVers.setEese05PpyverProposalUserC(user.getId());
            payPolVers.setEese05PpyverProposalS(new Timestamp(System
                    .currentTimeMillis()));
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        request.setAttribute("payPolVersSelected", payPolVers);
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward approve(FordActionMapping mapping,
                                 ActionForm actionForm,
                                 HttpServletRequest request,
                                 HttpServletResponse response,
                                 WebSession webSession, ActionMessages msgs,
                                 ActionMessages warns, ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        PaymentPolicyDefinitionForm form = (PaymentPolicyDefinitionForm) actionForm;
        PaymentPolicyFacade facade = (PaymentPolicyFacade) FacadeProvider
                .getFacade(request, PaymentPolicyFacade.class);
        Teese05Paypolvers payPolVers = form.getPayPolVersSelected();
        try {
            facade.approvePaymentPolicy(payPolVers, user);
            payPolVers.setEese05PpyverApprovalUserC(user.getId());
            payPolVers.setEese05PpyverApprovalS(new Timestamp(System
                    .currentTimeMillis()));

        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        
        request.setAttribute("payPolVersSelected", payPolVers);
        return mapping.findForward("success");
    }
    
    /**
     * lleva seteal el pp seleccionado y regresa a full economics
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward setPpInFullEconomic(FordActionMapping mapping,
                                             ActionForm actionForm,
                                             HttpServletRequest request,
                                             HttpServletResponse response,
                                             WebSession webSession,
                                             ActionMessages msgs,
                                             ActionMessages warns,
                                             ActionMessages errorMsgs) {

        PaymentPolicyDefinitionForm form = (PaymentPolicyDefinitionForm) actionForm;
        Teese05Paypolvers payPolVers = form.getPayPolVersSelected();
        form.getFullEconomic().getRowSelected().setPayPolVers(payPolVers);
        request.setAttribute("fullEconomicWrap", form.getFullEconomic());
        return mapping.findForward("success");
    }


}
